import { toRefs, ref } from "vue"
//导入map
import { useMapStore } from "@/stores/mapStore"
const { mapState } = toRefs(useMapStore())
export const useToolsBox = () => {
  var sketch
  var measureTooltipElement
  //定义画笔
  let draw = ref(null)
  //定义source
  let source = ref(null)
  let vector = ref(null)
  var listener
  var output
  //定义提示信息
  let helpTooltip
  let measureTooltip
  //定义样式
  var style = new ol.style.Style({
    //绘制几何图形的样式
    fill: new ol.style.Fill({
      color: "rgba(255, 255, 255, 0.5)",
    }),
    stroke: new ol.style.Stroke({
      color: "#198ce2",
      width: 2,
    }),
    image: new ol.style.Circle({
      radius: 5,
      stroke: new ol.style.Stroke({
        color: "red",
      }),
      fill: new ol.style.Fill({
        color: "rgba(255, 255, 255, 0.5)",
      }),
    }),
  })
  source.value = new ol.source.Vector()
  //加载测量的绘制矢量层
  vector.value = new ol.layer.Vector({
    source: source.value,
    style,
  })
  setTimeout(() => {
    //图层数据源
    mapState.value.map.addLayer(vector.value)
  }, 200)
  //定义overlayer,便于删除
  var drawElements = ref([])
  function measureMap(type) {
    if (draw.value) {
      mapState.value.map.removeInteraction(draw.value)
    }
    /**
     * 加载交互绘制控件函数
     */
    function addInteraction() {
      draw.value = new ol.interaction.Draw({
        source: source.value, //测量绘制层数据源
        type, //几何图形类型
        style,
      })
      mapState.value.map.addInteraction(draw.value)
      createMeasureTooltip() //创建测量工具提示框
      // createHelpTooltip() //创建帮助提示框

      //绑定交互绘制工具开始绘制的事件
      draw.value.on(
        "drawstart",
        function (evt) {
          // set sketch
          sketch = evt.feature //绘制的要素
          var tooltipCoord = evt.coordinate // 绘制的坐标
          //绑定change事件，根据绘制几何类型得到测量长度值或面积值，并将其设置到测量工具提示框中显示
          listener = sketch.getGeometry().on("change", function (evt) {
            var geom = evt.target //绘制几何要素

            if (geom instanceof ol.geom.Polygon) {
              output = formatArea(/** @type {ol.geom.Polygon} */ (geom)) //面积值
              tooltipCoord = geom.getInteriorPoint().getCoordinates() //坐标
            } else if (geom instanceof ol.geom.LineString) {
              output = formatLength(/** @type {ol.geom.LineString} */ (geom)) //长度值
              tooltipCoord = geom.getLastCoordinate() //坐标
            }
            measureTooltipElement.innerHTML = output //将测量值设置到测量工具提示框中显示
            measureTooltip.setPosition(tooltipCoord) //设置测量工具提示框的显示位置
          })
        },
        this
      )
      //绑定交互绘制工具结束绘制的事件
      draw.value.on(
        "drawend",
        function (evt) {
          measureTooltipElement.className = "tooltip tooltip-static" //设置测量提示框的样式
          measureTooltip.setOffset([0, -7])
          // unset sketch
          sketch = null //置空当前绘制的要素对象
          // unset tooltip so that a new one can be created
          measureTooltipElement = null //置空测量工具提示框对象
          createMeasureTooltip() //重新创建一个测试工具提示框显示结果
          ol.Observable.unByKey(listener)
        },
        this
      )
    }

    addInteraction()
  }
  function createMeasureTooltip() {
    if (measureTooltipElement) {
      measureTooltipElement.parentNode.removeChild(measureTooltipElement)
    }
    measureTooltipElement = document.createElement("div")
    measureTooltipElement.className = "tooltip tooltip-measure"
    measureTooltip = new ol.Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      positioning: "bottom-center",
    })
    mapState.value.map.addOverlay(measureTooltip)
    drawElements.value.push(measureTooltip)
  }
  var formatLength = function (line) {
    var length
    var sphere = new ol.Sphere()
    var sourceProj = mapState.value.map.getView().getProjection() //地图数据源投影坐标系
    length = sphere.getLength(line, {
      projection: sourceProj,
      radius: 6378137,
    })
    var output
    if (length > 100) {
      output = Math.round((length / 1000) * 100) / 100 + " " + "km" //换算成KM单位
    } else {
      output = Math.round(length * 100) / 100 + " " + "m" //m为单位
    }
    return output //返回线的长度
  }
  var formatArea = function (polygon) {
    var area
    var sphere = new ol.Sphere()
    var sourceProj = mapState.value.map.getView().getProjection() //地图数据源投影坐标系
    var geom = /** @type {ol.geom.Polygon} */ (
      polygon.clone().transform(sourceProj, "EPSG:4326")
    ) //将多边形要素坐标系投影为EPSG:4326
    area = Math.abs(
      sphere.getArea(geom, { projection: sourceProj, radius: 6378137 })
    ) //获取面积
    var output
    if (area > 10000) {
      output = Math.round((area / 1000000) * 100) / 100 + " " + "km<sup>2</sup>" //换算成KM单位
    } else {
      output = Math.round(area * 100) / 100 + " " + "m<sup>2</sup>" //m为单位
    }
    return output //返回多边形的面积
  }
  //关闭测量函数
  const closeMeasure = () => {
    // 移除之前存放长度和距离的图层
    drawElements.value.forEach((item) => {
      mapState.value.map.removeOverlay(item)
    })
    source.value.clear()
    mapState.value.map.removeInteraction(draw.value)
    mapState.value.map.removeLayer(vector)
    mapState.value.map.removeOverlay(helpTooltip)
  }
  function exportPdf() {
    mapState.value.map.once("postcompose", function (event) {
      var canvas = event.context.canvas
      var data = canvas.toDataURL("image/jpeg")
      var pdf = new jsPDF("landscape", undefined)
      pdf.addImage(data, "JPEG", 0, 0)
      pdf.save("map.pdf")
    })
    mapState.value.map.renderSync()
  }
  return { measureMap, closeMeasure, exportPdf }
}
